﻿using SmartDevice.Library.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SmartDevice.Library.Device.Voltmeter
{
    public class DC300Voltmeter : IVoltageVoltmeter
    {
        private readonly SerialPort spCom = new SerialPort();

        public event VoltageReportEventHandler VoltagesReport;

        public DC300Voltmeter()
        {
            spCom.DataReceived += SpCom_DataReceived;
        }

        public bool Connect(string SerialPortName)
        {
            try
            {
                spCom.PortName = SerialPortName;
                spCom.Open();

                Task.Run(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(500);
                        if (spCom.IsOpen)
                        {
                            //询问： 01 06 01 00 E0 49
                            byte[] senddata = new byte[] { 0x01, 0x06, 0x01, 0x00, 0xE0, 0x49 };
                            spCom.Write(senddata, 0, 6);
                        }
                        else
                        {
                            break;
                        }
                    }
                });

                return true;
            }
            catch { return false; }
        }

        public void Disconnect()
        {
            spCom.Close();
        }

        private void SpCom_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int Count = spCom.BytesToRead;
            byte[] buffer = new byte[Count];
            int bytes = spCom.Read(buffer, 0, Count);

            Debug.WriteLine(ConvertHelper.ByteArrayToHexString(buffer));

            //响应协议 01 06 01 02 00 00 00 00
            if (bytes == 8 && buffer[0] == 0x01 && buffer[1] == 0x06 && buffer[2] == 0x01 && buffer[3] == 0x02)
            {
                ushort Voltage = BitConverter.ToUInt16(buffer, 4);
                VoltagesReport?.Invoke(new VoltageReportEventArgs { Voltage = Voltage });
            }
        }
    }
}
